package cn.com.header.web.service.sys;

import cn.com.header.web.mapper.sys.AttachmentDao;
import cn.com.header.web.model.sys.Attachment;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Service
public class AttachServiceImpl implements AttachService{
	@Autowired
	AttachmentDao attachDao;
	private FileNameMap fileNameMap = URLConnection.getFileNameMap();

	public void writeAndSave(Attachment attach, InputStream input,HttpServletRequest request) {
		writeFile(attach, input,request);
		// 判断并设置文件类型
		if (attach.getPath().toLowerCase().endsWith(".bmp")) {
			attach.setFileType("image/bmp");
		}else if(attach.getPath().toLowerCase().endsWith(".mp3")||attach.getPath().toLowerCase().endsWith(".mp4")){
			attach.setFileType("mp3/mp4");
		}else {
			String fileType = fileNameMap.getContentTypeFor(getRootPath(request) + attach.getPath());

			if (fileType != null) {
				attach.setFileType(fileType);
			}
		}
		attach.setCreateTime(new Date());

		attachDao.insert(attach);
	}
	/**
	 * 保存附件，同时设置attach参数的文件路径和文件大小
	 *
	 * @param attach
	 *            附件实体对象
	 * @param input
	 *            文件输入流， 自动关闭
	 */
	public void writeFile(Attachment attach, InputStream input,HttpServletRequest request) {
		String rootPath = getRootPath(request);
		String savePath = generateFileSavePath(getRootPath(request), attach.getFileName(), attach.getType());
		try {
			OutputStream output = new FileOutputStream(rootPath + savePath);
			IOUtils.copy(input, output);
			output.close();
			input.close();
			attach.setPath(savePath);
			attach.setFileSize(new File(getRootPath(request) + savePath).length());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}



	/**
	 * Web版生成附件的保存路径，不包含根路径。 文件的保存路径格式为：根 + 类型 + 年份 + 时间串 + 文件后缀
	 */
	public String generateFileSavePath(String rootPath, String origName, Attachment.Type attachType) {
		// 获取随机码
		String uuid = UUID.randomUUID().toString();
		int i = origName.lastIndexOf('.');
		String ext = i > -1 ? origName.substring(i) : ""; // 文件后缀名
		SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
		String savePath = attachType.name() + "/" + format.format(new Date())+ "/"+uuid+ext;
		// 确保目录已被创建
		File file = new File(rootPath + savePath);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		return savePath;
	}

	
	public Attachment loadAttach(Long id) {
		Attachment attach = attachDao.get(id);
		return attach;
	}


	public InputStream getFileInputStream(Long attachId, HttpServletRequest request) throws Exception {
		Attachment attach = attachDao.get(attachId);
		return new FileInputStream(getRootPath(request) + attach.getPath());
	}

	private String getRootPath(HttpServletRequest request) {
		return request.getSession().getServletContext().getRealPath("/");
	}

		
}
